import 'package:flutter_riverpod/flutter_riverpod.dart';

import 'api_result.dart';
import 'http_client.dart';

/// 基础Repository类
abstract class BaseRepository {
  BaseRepository(this._httpClient);

  final HttpClient _httpClient;
  
  /// 暴露httpClient给子类使用（用于获取baseUrl等信息）
  HttpClient get httpClient => _httpClient;

  /// GET请求
  Future<ApiResult<T>> get<T>(
    String path, {
    Map<String, dynamic>? queryParameters,
    T Function(Map<String, dynamic>)? fromJson,
  }) => _httpClient.get<T>(path, queryParameters: queryParameters, fromJson: fromJson);

  /// POST请求
  Future<ApiResult<T>> post<T>(
    String path, {
    dynamic data,
    Map<String, dynamic>? queryParameters,
    T Function(Map<String, dynamic>)? fromJson,
  }) => _httpClient.post<T>(path, data: data, queryParameters: queryParameters, fromJson: fromJson);

  /// PUT请求
  Future<ApiResult<T>> put<T>(
    String path, {
    dynamic data,
    Map<String, dynamic>? queryParameters,
    T Function(Map<String, dynamic>)? fromJson,
  }) => _httpClient.put<T>(path, data: data, queryParameters: queryParameters, fromJson: fromJson);

  /// DELETE请求
  Future<ApiResult<T>> delete<T>(
    String path, {
    dynamic data,
    Map<String, dynamic>? queryParameters,
    T Function(Map<String, dynamic>)? fromJson,
  }) => _httpClient.delete<T>(path, data: data, queryParameters: queryParameters, fromJson: fromJson);

  /// PATCH请求
  Future<ApiResult<T>> patch<T>(
    String path, {
    dynamic data,
    Map<String, dynamic>? queryParameters,
    T Function(Map<String, dynamic>)? fromJson,
  }) => _httpClient.patch<T>(path, data: data, queryParameters: queryParameters, fromJson: fromJson);
}

/// Repository Provider Mixin
mixin RepositoryProviderMixin {
  /// 创建Repository Provider
  static Provider<T> create<T extends BaseRepository>(
    T Function(HttpClient httpClient) create,
  ) {
    return Provider<T>((ref) {
      final httpClient = ref.watch(reactiveHttpClientProvider);
      return create(httpClient);
    });
  }
}

